﻿using System;
using System.Collections.Generic;
using System.IO;

namespace RatingAuthor
{
  /// <summary>Represents pages cache. Translates page index to and from file path.</summary>
  /// <remarks>
  ///   Instances of this calss are fully thread safe.  
  ///   All methods do nothing but IO operations which are safe by means of OS.
  /// </remarks>
  public class PagesCache
  {
    private const string Folder = "Cache";
    public static void DeleteAll(Action<double> progress)
    {
      var list = Directory.GetFiles(Folder);
      var count = (double) list.Length;
      for (int i = 0; i < list.Length; i++)
      {
        try
        {
          File.Delete(list[i]);
        }
        catch (Exception x)
        {
          Console.WriteLine(x);
        }
        progress(i/count);
      }
      try
      {
        Directory.Delete(Folder, true);
      }
      catch (Exception x)
      {
        Console.WriteLine(x);
      }
      progress(1);
    }
    private readonly string _folder;
    private readonly List<Page> _cachedFiles = new List<Page>();

    public List<Page> CachedFiles
    {
      get { return _cachedFiles; }
    }

    public string GetFileName(int index)
    {
      return string.Format(_folder + @"\index-{0}.shtml", index);
    }

    public bool IsCached(int index)
    {
      return File.Exists(GetFileName(index));
    }

    public PagesCache(string cacheFolder)
    {
      _folder = Folder + "\\" + cacheFolder;

      if (!Directory.Exists(_folder))
      {
        Directory.CreateDirectory(_folder);
        return;
      }
      
      foreach (var file in Directory.GetFiles(_folder))
        _cachedFiles.Add(new Page(file, GetIndexByFileName(file)));
    }

    private static int GetIndexByFileName(string file)
    {
      var fn = Path.GetFileNameWithoutExtension(file);
      if (fn == null) throw new InvalidOperationException();
      return int.Parse(fn.Split('-')[1]);
    }
  }
}